package com.wzapp.sitposture.authentication.endpoint;


import com.alibaba.fastjson.JSONObject;
import com.wzapp.sitposture.authentication.service.CustomizedDefaultTokenServices;
import com.wzapp.sitposture.common.restful.RestfulResult;
import com.wzapp.sitposture.common.support.HttpKit;
import com.wzapp.sitposture.common.util.HeaderUtil;
import com.wzapp.sitposture.common.util.ToolUtil;
import com.wzapp.sitposture.config.redis.service.RedisService;
import com.wzapp.sitposture.event.BusinessEvent;
import com.wzapp.sitposture.usercenter.service.UserService;
import com.wzapp.sitposture.usercenter.view.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;
import java.util.HashMap;

/**
 * Created by ql on 2018/6/24.
 */
@FrameworkEndpoint
@Slf4j
public class RevokeTokenEndpoint {

    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    CustomizedDefaultTokenServices consumerTokenServices;

    @Autowired
    UserService userService;

    @Autowired
    RedisService redisService;

    @RequestMapping(method = RequestMethod.DELETE, value = "/oauth/token")
    @ResponseBody
    public ResponseEntity revokeToken(String access_token, Principal clientPrincipal) {

        JSONObject result = new JSONObject();
        String userId = consumerTokenServices.findUserId(access_token);
        if (null == userId) {
            result.put("message", "注销成功");
            result.put("actionTime", System.currentTimeMillis());
            return RestfulResult.createSuccess(result);
        }

        if (consumerTokenServices.revokeToken(access_token)) {
            result.put("message", "注销成功");
        } else {
            result.put("message", "注销失败");
        }
        result.put("actionTime", System.currentTimeMillis());

        UserDTO userDTO = userService.getSimpleUserById(userId);
        String tokenKey = "APP_USER_LIMIT_" + userDTO.getMobile();
        Object limitObject = redisService.get(tokenKey);
        int limitCount = 0;
        if(ToolUtil.isNotEmpty(limitObject)){
            limitCount = Integer.parseInt(limitObject.toString()) - 1;
            if(limitCount < 0){
                limitCount = 0;
            }
        }

        redisService.set(tokenKey,limitCount);

        //记录到登出日志
        saveToLogoutLog(userId, clientPrincipal);

        return RestfulResult.createSuccess(result);
    }

    private void saveToLogoutLog(String userId, Principal clientPrincipal) {
        if (null == userId) {
            log.error("====================错误的客户端登出，请使用用户权限的账户登出，客户端：{}", clientPrincipal.getName());
            return;
        }
        log.error("====================客户端登出成功，客户端：{}，userId:{}", clientPrincipal.getName(), userId);

        HashMap<String, Object> param = new HashMap<String, Object>(3);
        param.put("userId", userId);
        param.put("logoutTime", System.currentTimeMillis());
        param.put("terminalType", HeaderUtil.getHeaderParam(HttpKit.getRequest()).getTerminalType());
        applicationContext.publishEvent(new BusinessEvent(this, "userLogOut", param));
    }
}
